package com.zyw.module.console.user.controller;

import com.zyw.module.console.user.po.User;
import com.zyw.module.console.user.service.UserService;
import com.zyw.module.console.user.vo.UserListVo;
import com.zyw.mvc.servlet.BaseController;
import com.zyw.mvc.support.QueryResult;
import com.zyw.mvc.support.WrappedResult;
import com.zyw.orm.support.page.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("${path.console.prefix}/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @RequestMapping("get")
    @ResponseBody
    public WrappedResult get(Integer id) {
        return wrappedSuccessResult(userService.get(id));
    }

    @RequestMapping("save")
    @ResponseBody
    public WrappedResult save(User user) {
        int i = userService.insert(user);
        if (i > 0) {
            return wrappedSuccessResult(null);
        } else {
            return wrappedFaliedResult("保存失败");
        }
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public WrappedResult query(Page<User> page, User po) {

        page.setParamBean(po);

        List<User> list = this.userService.findByPage(page);
        List<UserListVo> vos = new ArrayList<>();
        if (!list.isEmpty()) {
            for (User user : list) {
                vos.add(UserListVo.toVo(user));
            }
        }

        QueryResult.QueryItem queryItem = new QueryResult.QueryItem();
        queryItem.setRows(vos);
        queryItem.setTotal(page.getTotal());
        return wrappedSuccessResult(queryItem, "查询成功");
    }
}